package com.sc.sc250601.cook.service.impl;

import com.sc.sc250601.cook.mapper.FavoriteMapper;
import com.sc.sc250601.cook.mapper.RecipeMapper;
import com.sc.sc250601.cook.pojo.BrowseRecord;
import com.sc.sc250601.cook.pojo.Favorite;
import com.sc.sc250601.cook.pojo.FavoriteResultDTO;
import com.sc.sc250601.cook.pojo.RecipeBrowseDTO;
import com.sc.sc250601.cook.service.FavoriteService;
import com.sc.sc250601.cook.service.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private RecipeMapper recipeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FavoriteResultDTO add(Favorite f) {
        //TODO 可优化，Redisson分布式锁
        // 保证多个用户同时收藏时，只有一个用户成功，其他用户重试

        // 先判断是否已收藏
        Favorite favorite = favoriteMapper.selectByUserIdAndFavoritedIdAndFavoritedType(f);
        if(favorite != null){
            // 取消收藏关系
            int i = favoriteMapper.deleteFavorited(f);
            // 帖子收藏次数-1
            int i1 =recipeMapper.updateFavoriteCountDecrease(f.getFavoritedId());
            if(i <= 0 || i1 <= 0){
                throw new RuntimeException("取消收藏失败"); // 抛异常，事务自动回滚
            }
            return new FavoriteResultDTO("unfavorited", "取消收藏成功");
        }
        // 添加收藏关系
        int i = favoriteMapper.insertSelective(f);
        // 对应帖子收藏次数+1
        int i1 = recipeMapper.updateFavoriteCountIncrease(f.getFavoritedId());
        if(i <= 0 || i1 <= 0){
            throw new RuntimeException("收藏失败");
        }
        return new FavoriteResultDTO("favorited", "收藏成功");
    }

    @Override
    public List<RecipeBrowseDTO> getFavoriteList(Long userId) {
        return favoriteMapper.getFavoriteList(userId);
    }
}
